package com.xhsj.user.pms.oareply.service;

import com.xhsj.user.generalprocess.service.TbPamGeneralProcessTaskService;
import com.xhsj.user.generalprocess.vo.GeneralAuditVo;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.pms.oareply.dto.*;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaCorrection;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaRecheck;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOaRecheckFile;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaRecheckFileMapper;
import com.xhsj.user.pms.oareply.mapper.TbPamPatentOaRecheckMapper;
import com.xhsj.user.pms.oareply.service.TbPamPatentOaRecheckService;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.pms.oareply.vo.CorrectionFileListVo;
import com.xhsj.user.pms.oareply.vo.FindToAuditVo;
import com.xhsj.user.pms.oareply.vo.ProcessTableNameVo;
import com.xhsj.user.properties.RoleKeyNameProperites;
import com.xhsj.user.utils.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;

/**
 * <p>
 * 专利OA复审 服务实现类
 * </p>
 *
 * @author liuqinghua
 * @since Jul 28, 2021 8:20:11 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbPamPatentOaRecheckService extends BaseService<TbPamPatentOaRecheckMapper, TbPamPatentOaRecheck>{
    @Autowired
    private TbPamPatentOaRecheckMapper dao;

    @Autowired
    private TbPamGeneralProcessTaskService tbPamGeneralProcessTaskService;

    @Autowired
    private TbPamPatentOaRecheckFileService tbPamPatentOaRecheckFileService;

    @Autowired
    private TbPamPatentOaRecheckFileMapper tbPamPatentOaRecheckFileMapper;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    @Autowired
    private RoleKeyNameProperites roleKeyNameProperites;

    //角色名称 知产部负责人
    @Value("${rolekeyname.zszl1}")
    private String zszl1;
	/**
	 * 保存
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:20:11 AM
	 */
    @Override
    public boolean save(TbPamPatentOaRecheck entity) {
        return super.save(entity);
    }

	/**
	 * 通过id获取数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:20:11 AM
	 */
    @Override
    public TbPamPatentOaRecheck getById(Serializable id) {
        return super.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:20:11 AM
	 */
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 分页查询数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:20:11 AM
	 */
    public IPage<TbPamPatentOaRecheck> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbPamPatentOaRecheck entity = JSON.parseObject(JSON.toJSONString(data), TbPamPatentOaRecheck.class);
        Page<TbPamPatentOaRecheck> page = new Page(currentPage,pageSize);
        QueryWrapper<TbPamPatentOaRecheck> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:20:11 AM
	 */
    @Override
    public List<TbPamPatentOaRecheck> selectAll() {
        return super.selectAll();
    }

    /**
     * @Description: 专利OA驳回流程启动
     * @Author: liuqinghua
     * @Date: 2021/8/03
     */
    public void startOARecheckProcess(StartOARecheckProcessDto param) throws Exception {
        // 保存申请表
        TbPamPatentOaRecheck tbPamPatentOaRecheck = new TbPamPatentOaRecheck();
        BeanUtils.copyProperties(param,tbPamPatentOaRecheck);
        if(!super.save(tbPamPatentOaRecheck))
            throw new Exception("OA答复模块-OA驳回保存申请表错误");
        // 执行流程
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        BeanUtils.copyProperties(param,generalAuditVo);
        generalAuditVo.setDataId(tbPamPatentOaRecheck.getId());
        this.setProcessTable(generalAuditVo);
        // 审批人
        generalAuditVo.setUserIds(Arrays.asList(param.getIpr()));
        tbPamGeneralProcessTaskService.startProcess(generalAuditVo, generalCallableVo -> {
            tbPamPatentOaRecheck.setNodeId(generalCallableVo.getNodeId());
            tbPamPatentOaRecheck.setNodeName(generalCallableVo.getNodeName());
            // 修改申请表
            super.updateById(tbPamPatentOaRecheck);
        });
        // 保存文件
        this.saveFiles(param.getFiles(),tbPamPatentOaRecheck.getId());
    }

    /**
     * @Description:专利OA驳回-ipr/操作人审核/知识产权部\LED高级工艺工程师\总经理角色审核
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    public void iprZszl1LedGmProcess(Zszl1LedGmProcessDto param) throws Exception {
        if(param.getStatus() == 1){
            // 审批人
            param.setUserIds(Arrays.asList(param.getIpr()));
        }else if(param.getStatus() == 0){
            Long nodeId = param.getNodeId();
            String roleKeyName = null;
            String roleName = null;
            if (nodeId == 2L) {
                // 执行流程-知产部负责人
                roleKeyName = zszl1;
                roleName = "知产部负责人";
            } else if (nodeId == 3L) {
                // 执行流程-LED高级工艺工程师
                roleKeyName = roleKeyNameProperites.getLedSeniorProcessEngineer();
                roleName = "LED高级工艺工程师";
            } else if (nodeId == 4L) {
                // 执行流程-总经理角色
                roleKeyName = roleKeyNameProperites.getGeneralManager();
                roleName = "总经理角色";
            }else if (nodeId == 5L || nodeId == 6L) {
                // 执行流程-流程专员
                roleKeyName = roleKeyNameProperites.getAssistantName();
                roleName = "流程专员";
            }
            // 根据角色名查找角色
            List<Long> roleIds = tbGlobalUserService.checkRole(roleKeyName, roleName);
            // 检查角色下是否有用户
            tbGlobalUserService.checkRoleUserId(roleKeyName,roleName);
            param.setRoleIds(roleIds);
        }
        // 执行流程
        handleProcess(param,param.getIpr());
        // 保存文件
        List<TbPamPatentOaRecheckFile> files = param.getFiles();
        this.saveFiles(files,param.getDataId());
    }


    /**
     * @Description: 专利OA驳回-国知局审查
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    public void examinationProcess(ExaminationProcessDto param) throws Exception {
        // 执行流程
        handleProcess(param,param.getIpr());
        // 保存文件
        List<TbPamPatentOaRecheckFile> files = param.getFiles();
        this.saveFiles(files,param.getDataId());
    }


    public void setProcessTable(GeneralAuditVo generalAuditVo){
        ProcessTableNameVo vo = new ProcessTableNameVo();
        BeanUtils.copyProperties(vo,generalAuditVo);
        generalAuditVo.setProcessType("patent_fs");
    }

    // 保存文件
    public void saveFiles(List<TbPamPatentOaRecheckFile> files, Long dataId) throws Exception {
        if(files.size()>0){
            // 删除
            tbPamPatentOaRecheckFileService.deleteByDataId(dataId);
            // 新增
            for (TbPamPatentOaRecheckFile file : files) {
                file.setId(null);
                file.setOaCheckId(dataId);
                file.setCreateDate(file.getCreateDate()==null?new Date():file.getCreateDate());
                file.setUpdateDate(file.getUpdateDate()==null?new Date():file.getUpdateDate());
                file.setCreateBy(file.getCreateBy()==null?UserUtils.getLoginAppUser().getUserId():file.getCreateBy());
                file.setUpdateBy(file.getUpdateBy()==null?UserUtils.getLoginAppUser().getUserId():file.getUpdateBy());
                if(tbPamPatentOaRecheckFileMapper.insert(file) != 1)
                    throw new Exception("OA答复模块-OA驳回保存文件错误");
            }
        }
    }

    /**
     * @Description: 专利OA驳回-待审核
     * @Author: liuqinghua
     * @Date: 2021/8/3
     */
    public IPage<FindToAuditVo> findToAudit(FindToAuditDto param) {
        Long userId = UserUtils.getLoginAppUser().getUserId();
        // 根据用户名获取角色
        List<Long> roleListByUserId = tbGlobalUserMapper.getRoleIdsByUserId(userId);
        param.setUserId(userId);
        param.setRoleIds(roleListByUserId);
        // 获取待审核列表
        Page<FindToAuditDto> page = new Page(param.getPage(),param.getPageSize());
        return dao.findToAudit(page,param);
    }

    /**
     * @Description: 专利OA驳回-审核通过
     * @Author: liuqinghua
     * @Date: 2021/8/3
     */
    public IPage<FindToAuditVo> findApproved(FindToAuditDto param) {
        Long userId = UserUtils.getLoginAppUser().getUserId();
        param.setUserId(userId);
        Page<FindToAuditDto> page = new Page(param.getPage(),param.getPageSize());
        return dao.findApproved(page,param);
    }
    /**
     * @Description:专利OA驳回-获取驳回文件
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    public IPage<CorrectionFileListVo> findReCheckFileList(Long dataId,Long page,Long pageSize) {
        return tbPamPatentOaRecheckFileService.findReCheckFileList(dataId,page,pageSize);
    }

    // 流程
    public void handleProcess(Object param,Long ipr) throws Exception {
        TbPamPatentOaRecheck tbPamPatentOaRecheck = new TbPamPatentOaRecheck();
        GeneralAuditVo generalAuditVo = new GeneralAuditVo();
        BeanUtils.copyProperties(param,generalAuditVo);
        this.setProcessTable(generalAuditVo);
        tbPamGeneralProcessTaskService.handleProcess(generalAuditVo,generalCallableVo -> {
            tbPamPatentOaRecheck.setNodeId(generalCallableVo.getNodeId());
            tbPamPatentOaRecheck.setNodeName(generalCallableVo.getNodeName());
            // 修改申请表
            tbPamPatentOaRecheck.setId(generalAuditVo.getDataId());
            tbPamPatentOaRecheck.setIpr(ipr);
            if(!super.updateById(tbPamPatentOaRecheck))
                throw new Exception("OA答复模块-OA驳回修改申请表错误");
        });
    }

    /**
     * @Description:专利OA驳回-获取驳回文件不分页
     * @Author: liuqinghua
     * @Date: 2021/8/4
     */
    public List<CorrectionFileListVo> findReCheckFileListNotPage(Long dataId) {
        return tbPamPatentOaRecheckFileService.findReCheckFileListNotPage(dataId);
    }
}
